<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>

<body>
    <div class="btns">
        <button data-path="/home">首页</button>
        <button data-path="/news">新闻</button>
        <button data-path="/music">音乐</button>
    </div>
    <div id="content"></div>
    <script>
        const oContent = document.getElementById("content");
        const routes = [
            { path: "/home", component: "我是首页啊" },
            { path: "/news", component: "这是一个热门新闻" },
            { path: "/music", component: "周杰伦发布新歌" },
        ];

        const oBtns = document.querySelectorAll(".btns button");
        oBtns.forEach((item) => {
            item.onclick = function () {
                history.pushState(null, null, this.dataset.path);
                routes.forEach((item) => {
                    if (item.path === this.dataset.path) {
                        oContent.innerHTML = item.component;
                    }
                });
            };
        });


        window.onpopstate = function () {
            console.log(location.pathname);
            routes.forEach((item) => {
                if (item.path === location.pathname) {
                    oContent.innerHTML = item.component;
                }
            });
        };
    </script>
</body>

</html>